package com.hmdp.service.impl;

import com.hmdp.dto.Result;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @desc  关注 和取消关注   查询是否关注
 * @author: weili23
 * @params
 * @Date: 2024/4/2 10:01
 * @version: 1.0
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private FollowMapper followMapper;

    @Resource
    private IUserService userService;
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //获取登录用户信息
        Long userId = UserHolder.getUser().getId();
        String key = "follows:"+userId;
        if(isFollow){
            //关注
            Follow follow = new Follow();
            follow.setFollowUserId(followUserId);
            follow.setUserId(userId);
            boolean save = save(follow);
            if(save){
                //把关注信息存到redis集合中
                stringRedisTemplate.opsForSet().add(key,followUserId.toString());
            }
        }else{
            //取关
            Integer integer = followMapper.cancelFollow(userId, followUserId);
            if(integer > 0){
                //把集合从redis中移除
                stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
            }
        }
        return Result.ok();
    }

    @Override
    public Result isFollow(Long followUserId) {
        //获取登录用户信息
        Long userId = UserHolder.getUser().getId();
        //1.查询是否关注
        Long count = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        //count > 0 说明是关注过的  返回true
        return Result.ok(count > 0);
    }

    @Override
    public Result followCommon(Long id) {
        Long userId = UserHolder.getUser().getId();
        String key = "follows:"+userId;
        String key2 = "follows:"+id;
        Set<String> strings = stringRedisTemplate.opsForSet().intersect(key, key2);
        if(strings == null || strings.isEmpty()){
            //无交集 返回空
            return Result.ok();
        }
        List<Long> ids = strings.stream().map(Long::valueOf).collect(Collectors.toList());
        List<User> users = userService.listByIds(ids);
        return Result.ok(users);
    }
}
